import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { CommonService } from 'src/app/services-common/common.service';
import { ConfigDefaultWordsService } from './config-default-words.service';

@Component({
  selector: 'app-config-default-words',
  templateUrl: './config-default-words.component.html',
  styleUrls: ['./config-default-words.component.scss']
})
export class ConfigDefaultWordsComponent implements OnInit {

  searchParams: any = {
    searchWord: '',
    searchBox: '',
    state: ''
  };

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  // 搜索框Options
  allChecked = false;
  indeterminate = false;
  searchInputOptions: any = [];

  // 新增 | 编辑 Modal
  isVisible: boolean = false;
  submitLoading: boolean = false;
  modalItem: any = null;
  validateForm!: FormGroup;

  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private commonService: CommonService,
    private services: ConfigDefaultWordsService
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      searchWord: ['', [Validators.required]],
      searchBox: [''],
      state: ['', [Validators.required]],
      remarks: ['']
    });
    
    // 查询搜索框字典
    this.querySearchInput();
    this.loadTable();
  }

  // 查询搜索框字典
  async querySearchInput() {
    this.searchInputOptions = [];
    const res = await this.commonService.getDictList('search_box');
    
    if (res && res.length) {
      res.forEach((ele: any) => {
        this.searchInputOptions.push({
          id: ele.id,
          value: ele.content,
          label: ele.name,
          checked: false
        })
      });
    }
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const res: any = await this.services.queryDefaultWordsList(params);
    this.tableParams.loading = false;
    
    if (res.code === 0) {
      const { records, total } = res.data || {};
      this.tableParams.tableData = records || [];
      this.tableParams.total = total || 0;
    } else {
      this.message.error(res.message);
    }
  }

  queryData() {
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData() {
    for (let key in this.searchParams) {
      this.searchParams[key] = '';
    }
    this.tableParams.page = 1;
    this.loadTable();
  }

  updateModal(type: number, item?: any) {
    this.modalItem = null;
    this.validateForm.reset();
    this.allChecked = false;
    this.indeterminate = false;
    this.searchInputOptions.map((item: any) => item.checked = false);

    if (type === 1) {
      this.modalItem = item;
      this.validateForm.patchValue({
        searchWord: item.searchWord || '',
        searchBox: item.searchBox || '',
        state: item.state,
        remarks: item.remarks || '',
      });

      if (item.searchBox) {
        // have
        if (item.searchBox == 0) {
          this.allChecked = true;
          this.searchInputOptions.map((item: any) => item.checked = true);
        } else {
          this.indeterminate = true;
          let tempArr = item.searchBox ? item.searchBox.split(',') : [];
          this.searchInputOptions.forEach((item: any) => {
            if (tempArr.includes(item.value)) {
              item.checked = true;
            } else {
              item.checked = false;
            }
          });
        }
      }
    }

    this.isVisible = true;
  }

  async updateSubmitForm() {
    if (this.validateForm.valid) {
      let params: any = {
        ...this.validateForm.value
      }
      let res: any;
      if (this.modalItem) {
        // Edit
        params.id = this.modalItem.id;
        res = await this.services.updateDefaultWordsItem(params);
      } else {
        // Add
        res = await this.services.saveDefaultWordsItem(params);
      }

      if (res.code === 0) {
        this.message.success('操作成功');
        this.isVisible = false;
        this.loadTable();
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  /**
   * ----------------------------------------------------------------
   * Modal搜索框全选处理
   * ----------------------------------------------------------------
   */
   updateAllChecked(): void {
    this.indeterminate = false;
    if (this.allChecked) {
      this.searchInputOptions = this.searchInputOptions.map((item: any) => ({
        ...item,
        checked: true
      }));
    } else {
      this.searchInputOptions = this.searchInputOptions.map((item: any) => ({
        ...item,
        checked: false
      }));
    }

    this.checkValueFilter();
  }
 
  updateSingleChecked(): void {
    if (this.searchInputOptions.every((item: any) => !item.checked)) {
      this.allChecked = false;
      this.indeterminate = false;
    } else if (this.searchInputOptions.every((item: any) => item.checked)) {
      this.allChecked = true;
      this.indeterminate = false;
    } else {
      this.indeterminate = true;
    }

    this.checkValueFilter();
  }

  // Check Box
  checkValueFilter() {
    let tempArr = [];
    tempArr = this.searchInputOptions.filter((item: any) => item.checked).map((tag: any) => tag.value);
    
    if (tempArr.length === this.searchInputOptions.length) {
      this.validateForm.get('searchBox')?.setValue('0');
    } else {
      this.validateForm.get('searchBox')?.setValue(tempArr.join(','));
    }
  }
}
